package br.com.musclebook.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.com.musclebook.entity.Routine;
import br.com.musclebook.entity.User;
import br.com.musclebook.entity.UserCurrentRoutine;

public class RoutineDAO extends BaseDAO {

    public Routine find(Long id) {
	EntityManager em = this.getEm();
	Query query = em.createNamedQuery("Routine.findById");
	query.setParameter("id", id);

	return (Routine) query.getSingleResult();
    }

    public Routine insert(Routine routine) {
	EntityManager em = this.getEm();
	routine.setCreation(new Date());
	em.persist(routine);
	return routine;
    }

    public Routine update(Routine routine) {
	EntityManager em = this.getEm();
	return em.merge(routine);
    }

    public boolean updateRating(Long routineId, Integer newRate) {
	EntityManager em = this.getEm();
	Query query = em.createNamedQuery("Routine.updateRate");
	query.setParameter("rate", newRate);
	query.setParameter("routineId", routineId);

	int updatedRows = query.executeUpdate();

	if (updatedRows > 0)
	    return true;
	else
	    return true;
    }

    public void delete(Long routineId) {
	EntityManager em = this.getEm();
	Routine routine = em.find(Routine.class, routineId);

	// if user is removing current default routine then update to null
	if (routine.isUserCurrentRoutine()) {
	    User user = routine.getUser();
	    
	    em.remove(user.getCurrentRoutine());
	    
	    user.setCurrentRoutine(null);
	    em.merge(user);
	    
	    
	}

	em.remove(routine);
    }

    public void setAsUserCurrent(Long routineId, Date start) {
	EntityManager em = this.getEm();

	Routine routine = em.find(Routine.class, routineId);
	User user = routine.getUser();
	
	if(user.getCurrentRoutine() != null) {
	    em.remove(user.getCurrentRoutine());
	}

	UserCurrentRoutine userCurrentRoutine = new UserCurrentRoutine(user, routine, start);

	user.setCurrentRoutine(userCurrentRoutine);

	em.merge(user);
    }

    @SuppressWarnings("unchecked")
    public List<Routine> list(Long userId) {
	EntityManager em = this.getEm();

	List<Routine> routines = new ArrayList<Routine>();

	Query query = em.createNamedQuery("Routine.list");
	query.setParameter("userId", userId);
	routines.addAll(query.getResultList());

	return routines;
    }

}
